import Taro, { useLoad } from '@tarojs/taro'
import { useCallback, useRef, useState } from 'react'
import { IGetList } from '@/api/methods/other.type'
import BtLayout from '@/BtComponents/BtLayout'
import BtFreshList from '@/BtComponents/BtFreshList'
import BtScroll from '@/BtComponents/BtScroll'
import utils from '@/utils'
import Cell from './cell'
import './index.scss'

export default function Index () {
  const [data, setData] = useState<IGetList.item[]>([])
  const params = useRef<IGetList.ReqParams>({})
  const listRef = useRef<any>(null)
  const [refreshing, setRefreshing] = useState(false)

  useLoad(async () => {
    await utils.$initPage()
    queryList()
  })

  const queryList = () => {
    params.current = {studentName: ''}
    listRef.current.request()
  }

// 处理下拉刷新
  const handleRefresh = async () => {
    setRefreshing(true)
    try {
      await listRef.current.reFresh()
      setRefreshing(false)
    } finally {
      setRefreshing(false)
    }
  }

  // 处理上拉加载
  const handleLoadMore = useCallback(async () => {
    await listRef.current.nextPage()
  }, [])

  return (
    <BtLayout>
      <BtScroll
        onRefresh={handleRefresh}
        onLoadMore={handleLoadMore}
        refresherTriggered={refreshing}
      >
        <BtFreshList ref={listRef} requestFc={utils.$apis.getList} setListData={setData} params={params} >
          {
            data.map(item => {
              return (
                <Cell key={item.id} item={item}></Cell>
              )
            })
          }
        </BtFreshList>
      </BtScroll>
    </BtLayout>
  )
}
